﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PJ.Data;

namespace PJ.Business
{
    /// <summary>
    /// EntityFragment class
    /// </summary>
    /// <typeparam name="OD">Inner data object</typeparam>
    public abstract class EntityFragment<OD> : BusinessObject<OD>, IEntityFragment
        where OD : IEntityFragmentData
    {
        private IEntity m_Parent;

        public EntityFragment(OD data)
            : base(data)
        {
        }
        public EntityFragment()
        {
        }

        public string ParentID
        {
            get
            {
                return ObjectData.ParentId;
            }
            set
            {
                if (ObjectData.ParentId != value)
                {
                    ObjectData.ParentId = value;
                    if (value == null)
                        m_Parent = null;
                    else
                        if (m_Parent != null)
                            if (m_Parent.Id != ParentID)
                                Parent = ParentService.FindById(ParentID);
                }
            }
        }

        public override void CopyFrom(IBusinessObject data)
        {
            base.CopyFrom(data);
            IEntityFragment idata = data as IEntityFragment;
            if (idata != null)
                this.ParentID = idata.ParentID;
        }

        protected abstract IEntityService ParentService { get; }


        public IEntity Parent 
        {
            get
            {
                if (m_Parent == null && !string.IsNullOrEmpty(ParentID))
                    Parent = ParentService.FindById(ParentID);
                return m_Parent;                
            }
            set
            {
                if (value != m_Parent)
                {
                    m_Parent = value;
                    if (value == null)
                        ParentID = null;
                    else
                        ParentID = value.GlobalId;
                }
            }
        }

    }

}

